#!/usr/bin/python
# -*- coding: UTF-8 -*-
# import MySQLdb
import time
import iso8601
import json
import os
import datetime
import helpers
from api.MojiApi import MojiApi 
from api.CityApi import CityApi 
from MongoDb import MongoDb 
from Logs import Logs 
from WilddogSDK import WilddogSDK
from flask import Flask

app = Flask(__name__)

@app.route('/')

def weather_moji():
    try:
        moji = MojiApi()
        bran = CityApi()
        wilddog = WilddogSDK()
        db = MongoDb()
        log = Logs()
        data = bran.getTargetCity()
        if data['code'] == 0 and data['data']:
            for row in data['data']['device']:
                city_id = row['_id']
                if row['coordinate']:
                    lat = str(row['coordinate']['latitude'])
                    lon = str(row['coordinate']['longitude'])
                    country_code = row['country_code']
                    name_cn = row['name_cn']
                    result = moji.getUrl(lat, lon, country_code)
                    if result != False and result['code'] == 0:
                        if country_code == 'CN':
                            weather_info = result['data']
                            condition = weather_info['condition']['condition']
                            sunRise = weather_info['condition']['sunRise']
                            sunSet = weather_info['condition']['sunSet']
                            humidity = weather_info['condition']['humidity']
                            pressure = weather_info['condition']['pressure']
                            temp = weather_info['condition']['temp']
                            windLevel = weather_info['condition']['windLevel']
                            windSpeed = weather_info['condition']['windSpeed']
                            aqi = weather_info['aqi']['value']
                            pm25 = weather_info['aqi']['pm25']
                            skycon = helpers.weather_switch(condition, sunRise, sunSet)
                        else:
                            weather_info = result
                            condition = weather_info['condition']['condition']
                            sunRise = ''
                            sunSet = ''
                            humidity = weather_info['condition']['humidity']
                            pressure = weather_info['condition']['pressure']
                            temp = weather_info['condition']['temperature']
                            windLevel = ''
                            windSpeed = weather_info['condition']['windSpeed']
                            aqi = ''
                            pm25 = ''
                            skycon = helpers.weather_switch(condition, sunRise, sunSet)
                        data_info = {
                            'aqi': aqi,
                            'cloudrate': '',
                            'humidity': humidity,
                            'name_cn': name_cn,
                            'pm25': pm25,
                            'precipitation': '',
                            'pres': pressure,
                            'skycon': skycon,
                            'temperature': temp,
                            'timestamp': time.time(),
                            'wind':{
                                'direction': windLevel,
                                'speed': windSpeed
                            }
                        }
                        wilddog.insert_weather(city_id + "/weather", data_info);
                        db.insertWeatherToDb(city_id, data_info)
                        # loginfo = row['country'].encode('utf-8') + '-' + row['name_cn'].encode('utf-8')+ '-'  + city_id.encode('utf-8')  + '--天气数据采集成功！'
                        # log.logwrite(loginfo, 'weather')
                    else:
                        return '墨迹API执行失败'
            return '墨迹天气抓取成功！'
        else:
            return '读取加入城市数据失败！'
    except Exception, e:
        return e.message     

if __name__ == '__main__':
    app.run(host='', port=int(os.environ['PORT']), debug=True)
